from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import memoize
from my315ok.fangcan.interfaces import Ihouse

from my315ok.fangcan import fangcanMessageFactory as _


class IsubdistrictView(Interface):
    """
    subdistrict view interface
    """

    def test():
        """ test method"""


class subdistrictView(BrowserView):
    """
    subdistrict browser view
    """
    implements(IsubdistrictView)

    def __init__(self, context, request):
        self.context = context
        self.request = request

    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def portal(self):
        return getToolByName(self.context, 'portal_url').getPortalObject()

    def test(self,t,a,b):
        """ test method"""   
        if t:
            return a
        else:
            return b
    
    def getGreening_ratio(self):
        ratio = self.context.getGreening_ratio()
        if ratio ==None:
            ratio = 0
        ratio = ratio * 100
        if ratio == None:
            return ""
        out = "%1.2f" % ratio + "%"
        return out
    def getCapacity_ratio(self):
        ratio = self.context.getCapacity_ratio()
        if ratio ==None:
            ratio = 0
        ratio = ratio * 100
        if ratio == None:
            return ""
        out = "%1.2f" % ratio + "%"
        return out
    
    
        
    def averageprice(self):
        category="secondhand house"
        bns = self.get_brains(category)
        total = len(bns)
        if total ==0:
            return '%1.2f' % 0
        sum = 0
        for bn in bns:
            sum = sum + bn.Sale_unitprice
        average = sum/total
        average = '%1.2f' % average
        return average
        
        
    def secondhandamount(self,category="secondhand house"):
        bns = self.get_brains(category)
        return len(bns)
    def newhouseamount(self,category="new house"):
        bns = self.get_brains(category)
        return len(bns)
    def rentamount(self,category="rend house"):
        bns = self.get_brains(category)
        return len(bns)
        
    @memoize
    def get_brains(self,category):
        """ Fetches the last contract (or letter) of the
        employee (last in the meaning 'The one that ends the later'
        not 'The last one created'.)
        """
#        contentFilter = {'portal_type': ['Contract', 'Letter']}

#        import pdb
#        pdb.set_trace()
#        context = aq_inner(self.context)
#        tools = getMultiAdapter((context, self.request), name=u'plone_tools')

        name = self.context.Title()
        pc = getToolByName(self.context, 'portal_catalog')
        brains = pc(object_provides=Ihouse.__identifier__,
                             category=category,
                             Estate=name,
                             review_status='published',
                             sort="modified",
                             sort_order='reverse'
                             )
#        brains = self.getFolderContents(contentFilter=contentFilter)
        if not brains:
            return []
        return brains

    @memoize
    def map(self):
        """render the map of the house position"""
        
        out = """function initialize() {var myLatlng = new google.maps.LatLng(%s,%s);
        var myOptions = {
        zoom: 12,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        };
       var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
       var contentString = '<div id="map-mark">' + 
       '<a target="_blank" href="#">%s</a>' + '</div><br />' +
       '<span>%s</span>';
       var infowindow = new google.maps.InfoWindow({content: contentString});
       var marker = new google.maps.Marker({position: myLatlng,map: map,title:"%s"});
       infowindow.open(map,marker);    
       }
       jq('body').bind('onload',initialize())
       """ % (self.context.getLatitude(),self.context.getLongitude(),self.context.getArea(),self.context.getAddress(),self.context.getArea())
        return out
    
    @memoize
    def houseimage(self,scale="orig"):
        """fetch house main photo"""
#        bns = self.get_brains("secondhand house")
#        if len(bns) >=1:
#            bn = bns[0]
#        else:
#            return None
        alt = self.context.Title()
        base = self.context.absolute_url()
        if scale=="orig":
            ext = '/image'
        else:
            ext = '/image_' + scale
        url = base + ext
        portal = self.portal
#        import pdb
#        pdb.set_trace()
        p_url = portal.absolute_url()
        existimg = portal.unrestrictedTraverse(url, default=None)
        if existimg == None:
            url = p_url + "/++resource++fcwatermark_%s.jpg" % scale     
        html='<img src="%s" alt="%s" />' % (url,alt)
        return html
    
    @memoize
    def addfav(self):
        """<a onclick="javascript:window.external.AddFavorite('http://www.07312s.com/sale/d-2254.html',
        ' 城郊·馨香园二手房，2室2厅2卫1阳，韶山西路上豪装好房出售 - 湘潭找房网房源-韶山西路上豪装好房出售-城郊·馨香园');
        return false;" href="http://www.07312s.com/sale/d-2254.html" class="color690">收藏房源</a>"""
        url = self.context.absolute_url()
        title = self.context.Title()
        out ="javascript:window.external.AddFavorite('%s','%s');return false;" % (url,title)
        return out
